import { defineEventHandler } from 'h3'
import { getPool } from '../../util/mysql'
import { checkAdminKey, parsePaging, queryTableCount } from './_utils'

export default defineEventHandler(async (event: any) => {
  const ck = await checkAdminKey(event)
  if (!ck.ok) return { status: event.node.res.statusCode || 401, message: ck.message }

  const { page, pageSize, offset, search, start, end } = parsePaging(event)

  try {
    const pool = await getPool()
    const whereParts: string[] = ['WHERE is_deleted in (0,1)']
    const params: any[] = []
    if (search) {
      whereParts.push('(message LIKE ? OR id LIKE ?)')
      const s = `%${search}%`
      params.push(s, s)
    }
    if (start) {
      whereParts.push('create_time >= ?')
      params.push(start)
    }
    if (end) {
      whereParts.push('create_time <= ?')
      params.push(end)
    }
    const where = whereParts.length ? ' ' + whereParts.join(' AND ') : ''

    const total = await queryTableCount(pool, 'lin_payinfo', where, params)

    const safeLimit = Number(pageSize) || 20
    const safeOffset = Number(offset) || 0
    const [rows]: any = await pool.execute(
      `SELECT * FROM lin_payinfo ${where} ORDER BY create_time DESC LIMIT ${safeLimit} OFFSET ${safeOffset}`,
      params
    )

    return { data: rows || [], page, pageSize, total }
  } catch (err: any) {
    event.node.res.statusCode = 500
    const res: any = { status: 500, message: String(err?.message || err) }
    if (process.env.NODE_ENV !== 'production') res.stack = err?.stack
    return res
  }
})
